package im.agents.users;


import im.domain.Context;
import im.domain.XMLSerializer;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.proto.AchieveREInitiator;

/**
 * Agente "finto" che richiede il context di un nodo. Comunica con il ContextManager
 * tramite il protocollo FIPA-request
 * ELIMINARE QUESTA CLASSE
 * @author Silvia
 *
 */
public class ContextRequester extends Agent {
	
	public void setup(){
		super.setup();
		doWait(6000);
		ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
		request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
		request.setSender(this.getAID());
		DFAgentDescription[] ds = findContextManager();
		if(ds== null||ds.length<=0){
			System.out.println("CM not found");
		}else {
			request.addReceiver(ds[0].getName());
		//	System.out.println("MSG CONTEXTREQUESTER"+request.toString());
		//	System.out.println("RICHIESTA AL CONTEXT MANAGER"+ds[0].getName());
		}
		/*ACLMessage request2 = new ACLMessage(ACLMessage.REQUEST);
		request2.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
		request2.setSender(this.getAID());
		DFAgentDescription[] ds2 = findMigrationManager();
		if(ds2== null||ds2.length<=0){
			System.out.println("MM not found");
		}else {
			request.addReceiver(ds2[0].getName());
			System.out.println("MSG CONTEXTREQUESTER"+request2.toString());
			System.out.println("RICHIESTA AL MIGRATION MANAGER"+ds2[0].getName());
		}*/
	
		this.addBehaviour(new AchieveREInitiator(this,request){
			protected void handleInform(ACLMessage inform){
				XMLSerializer serializer = new XMLSerializer();
				//Context context = (Context) serializer.deserialize(inform.getContent());
				//System.out.println("SONO IL CONTEXT REQUESTER ricevuta risposta da"+inform.getSender());
			}
		});
	}
	
	private DFAgentDescription[] findContextManager() {
		DFAgentDescription[] ds = null;
		try {
			DFAgentDescription dfd = new DFAgentDescription();
			ServiceDescription s = new ServiceDescription ();
			s.setName("context-info");
			s.setType("context-info");
			dfd.addServices(s);
			ds = DFService.search(this, dfd);
			
		} catch (FIPAException e) {
			e.printStackTrace();
			return null;
		}
		return ds;
	}
	
	private DFAgentDescription[] findMigrationManager() {
		DFAgentDescription[] ds = null;
		try {
			DFAgentDescription dfd = new DFAgentDescription();
			ServiceDescription s = new ServiceDescription ();
			s.setName("migration-manager");
			s.setType("migration-manager");
			dfd.addServices(s);
			ds = DFService.search(this, dfd);
			
		} catch (FIPAException e) {
			e.printStackTrace();
			return null;
		}
		return ds;
	}


	
	

}
